<template>
  <div class="login-container">
    <div class="login-wrapper">
      <!-- 左侧背景区域 -->
      <div class="login-bg">
        <div class="bg-content">
          <h1 class="system-title">教育管理系统</h1>
          <p class="system-desc">智能化教育管理平台，提升教学效率</p>
          <div class="feature-list">
            <div class="feature-item">
              <el-icon><Document /></el-icon>
              <span>题库管理</span>
            </div>
            <div class="feature-item">
              <el-icon><Edit /></el-icon>
              <span>试卷制作</span>
            </div>
            <div class="feature-item">
              <el-icon><DataAnalysis /></el-icon>
              <span>成绩分析</span>
            </div>
            <div class="feature-item">
              <el-icon><User /></el-icon>
              <span>学员管理</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧登录表单 -->
      <div class="login-form-wrapper">
        <div class="login-form">
          <div class="form-header">
            <h2>管理员登录</h2>
            <p>请输入您的账号和密码</p>
          </div>
          
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form-content"
            @keyup.enter="handleLogin"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                size="large"
                prefix-icon="User"
                clearable
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                prefix-icon="Lock"
                show-password
                clearable
              />
            </el-form-item>
            
            <el-form-item v-if="showCaptcha" prop="captcha">
              <div class="captcha-wrapper">
                <el-input
                  v-model="loginForm.captcha"
                  placeholder="请输入验证码"
                  size="large"
                  prefix-icon="Key"
                  clearable
                  class="captcha-input"
                />
                <div class="captcha-image" @click="refreshCaptcha">
                  <img :src="captchaUrl" alt="验证码" />
                </div>
              </div>
            </el-form-item>
            
            <el-form-item>
              <div class="form-options">
                <el-checkbox v-model="loginForm.rememberMe">
                  记住密码
                </el-checkbox>
                <el-link type="primary" @click="handleForgotPassword">
                  忘记密码？
                </el-link>
              </div>
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                class="login-btn"
                :loading="loading"
                @click="handleLogin"
              >
                {{ loading ? '登录中...' : '登录' }}
              </el-button>
            </el-form-item>
          </el-form>
          
          <div class="form-footer">
            <p class="copyright">
              © 2024 教育管理系统. All rights reserved.
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Document, Edit, DataAnalysis, User } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { getToken, setToken } from '@/utils/auth'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const loginFormRef = ref()

// 加载状态
const loading = ref(false)

// 是否显示验证码
const showCaptcha = ref(false)

// 验证码URL
const captchaUrl = ref('')

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  rememberMe: false
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度为 4 位', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    // 调用登录接口
    const result = await userStore.login({
      username: loginForm.username,
      password: loginForm.password,
      captcha: showCaptcha.value ? loginForm.captcha : undefined
    })
    
    if (result.success) {
      ElMessage.success('登录成功')
      
      // 记住密码
      if (loginForm.rememberMe) {
        localStorage.setItem('rememberedUsername', loginForm.username)
      } else {
        localStorage.removeItem('rememberedUsername')
      }
      
      // 跳转到首页
      router.push('/')
    } else {
      ElMessage.error(result.message || '登录失败')
      
      // 登录失败后显示验证码
      if (!showCaptcha.value) {
        showCaptcha.value = true
        refreshCaptcha()
      }
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请稍后重试')
    
    // 显示验证码
    if (!showCaptcha.value) {
      showCaptcha.value = true
      refreshCaptcha()
    }
  } finally {
    loading.value = false
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  captchaUrl.value = `/api/auth/captcha?t=${Date.now()}`
}

// 处理忘记密码
const handleForgotPassword = () => {
  ElMessage.info('请联系系统管理员重置密码')
}

// 组件挂载时的处理
onMounted(() => {
  // 如果已经登录，直接跳转到首页
  if (getToken()) {
    router.push('/')
    return
  }
  
  // 恢复记住的用户名
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  if (rememberedUsername) {
    loginForm.username = rememberedUsername
    loginForm.rememberMe = true
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-4);
}

.login-wrapper {
  width: 100%;
  max-width: 1000px;
  background: white;
  border-radius: var(--border-radius-2xl);
  box-shadow: var(--shadow-xl);
  overflow: hidden;
  display: flex;
  min-height: 600px;
}

.login-bg {
  flex: 1;
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-12);
  color: white;
  
  @media (max-width: 768px) {
    display: none;
  }
}

.bg-content {
  text-align: center;
  max-width: 400px;
}

.system-title {
  font-size: var(--font-size-4xl);
  font-weight: 700;
  margin-bottom: var(--spacing-4);
  line-height: var(--line-height-tight);
}

.system-desc {
  font-size: var(--font-size-lg);
  opacity: 0.9;
  margin-bottom: var(--spacing-12);
  line-height: var(--line-height-relaxed);
}

.feature-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--spacing-6);
}

.feature-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-3);
  font-size: var(--font-size-base);
  opacity: 0.9;
  
  .el-icon {
    font-size: var(--font-size-xl);
  }
}

.login-form-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-8);
  
  @media (max-width: 768px) {
    padding: var(--spacing-6);
  }
}

.login-form {
  width: 100%;
  max-width: 400px;
}

.form-header {
  text-align: center;
  margin-bottom: var(--spacing-8);
  
  h2 {
    font-size: var(--font-size-3xl);
    font-weight: 600;
    color: var(--gray-800);
    margin-bottom: var(--spacing-2);
  }
  
  p {
    color: var(--gray-600);
    font-size: var(--font-size-base);
  }
}

.login-form-content {
  .el-form-item {
    margin-bottom: var(--spacing-6);
  }
}

.captcha-wrapper {
  display: flex;
  gap: var(--spacing-3);
  
  .captcha-input {
    flex: 1;
  }
  
  .captcha-image {
    width: 120px;
    height: 40px;
    border: 1px solid var(--el-border-color);
    border-radius: var(--border-radius);
    cursor: pointer;
    overflow: hidden;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: var(--font-size-lg);
  font-weight: 600;
  border-radius: var(--border-radius-lg);
}

.form-footer {
  text-align: center;
  margin-top: var(--spacing-8);
  
  .copyright {
    color: var(--gray-500);
    font-size: var(--font-size-sm);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-wrapper {
    margin: var(--spacing-4);
    min-height: auto;
  }
  
  .form-header {
    h2 {
      font-size: var(--font-size-2xl);
    }
  }
  
  .captcha-wrapper {
    flex-direction: column;
    
    .captcha-image {
      width: 100%;
      height: 50px;
    }
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: var(--spacing-2);
  }
  
  .login-form-wrapper {
    padding: var(--spacing-4);
  }
}
</style>